use strict;
use warnings;

package Lingua::EN::WSD::WebBased::Logger;

use base qw/Exporter/;

use Log::Log4perl qw/:easy/;
use Exporter;

use Carp qw/confess/;

use constant default_logging_level => $TRACE;

our @EXPORT = qw/
    set_logging_level _d _v
    _fatal _error _info _warn _debug _trace
    $FATAL $ERROR $INFO $WARN $DEBUG $TRACE
/;

my $initialized;

sub set_logging_level {

    my $level = shift;    
    Log::Log4perl->easy_init({
        level   => $level,
        file    => 'STDERR',
        layout  => '%d %m %n',#'%d %F(%L): %m %n',
    });

    $initialized = 1;

}

sub _d {
    
    use Data::Dumper;
    goto &Dumper;

}

sub _v {

    my $v = shift;
    my $r = '';
    for (sort { $v->{$b} <=> $v->{$a} } keys %$v) {
        $r .= "$_: $v->{$_}, ";
    }
    $r =~ s/, $//;
    return "[$r]";

}

sub AUTOLOAD {

    my $method = $Lingua::EN::WSD::WebBased::Logger::AUTOLOAD;

    if ($method =~ /_(fatal|error|info|warn|debug|trace)$/) {
        
        my $level = $1;
        my $opt = pop if ref $_[-1] eq 'HASH';
        my $depth_adjustment = $opt->{depth_adjustment} || 0;

        if (!$initialized) {
            _set_logging_level(default_logging_level);
            $initialized = 1;
        }
        
        $Log::Log4perl::caller_depth = 2 + $depth_adjustment;
        $Carp::CarpLevel = 1 + $depth_adjustment;
        
        eval "Log::Log4perl->get_logger->$level(\@_)";
        confess 'ERROR: "', @_, '"' if $level eq 'error';
        confess 'FATAL: "', @_, '"' if $level eq 'fatal';
    }

}

1;
